<template>
  <div :class="['nav-bread', { 'show': showBread }]">
    <Breadcrumb v-bind="$attrs" v-show="showBread">
      <BreadcrumbItem v-for="(t, idx) in breadMenus" :key="idx">
        <span @click="turnTo(t)">
          <Icon v-show="t.icon" :type="t.icon"></Icon>
          {{ t.title }}
        </span>
      </BreadcrumbItem>
    </Breadcrumb>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { typeOf } from "@libs/tools"; //引入核心库中

const findDeepPath = (data, path) => {
  if (Array.isArray(data) && data.length) {
    const has = (data, path) => {
      return data.some(it => {
        //先判断该元素是否相等
        if (it.path === path) {
          return true;
        }
        if (it.children && it.children.length) {
          return has(it.children, path);
        }
      });
    };
    //递归
    return has(data, path);
  } else {
    return false;
  }
};

const findAll = (data, to) => {
  const { path, name, query, params, meta, fullPath } = to;
  let arr = [];
  const findChild = (data, path) => {
    for (let item of data) {
      //先匹配子元素是否存在path
      if (findDeepPath(item.children, path)) {
        //若子元素存在
        arr.push({
          path: item.path,
          title: item.title,
          icon: item.title,
          to: item.to
        });
      }
      //匹配该元素是否存在path
      if (item.path === path) {
        item.to = {
          //更改原对象
          path,
          name,
          query,
          params,
          meta,
          fullPath
        };
        arr.push({
          path: item.path,
          title: item.title,
          icon: item.title,
          to: item.to
        });
      }
      //递归的条件
      if (item.children && item.children.length) {
        findChild(item.children, path);
      }
    }
  };
  //递归查找
  findChild(data, path); //根据menus,path: "/detail",寻找子集合
  return arr;
};

export default {
  name: "NavBread",
  props: {
    home: {
      //是否显示home
      type: Object,
      default: () => {
        return {};
      }
    },
    showOnlyOne: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      breadMenus: []
    };
  },
  computed: {
    ...mapState(["menus"]),
    showBread() {
      return this.showOnlyOne
        ? this.breadMenus.length > 0
        : this.breadMenus.length > 1;
    }
  },
  methods: {
    turnTo(item) {
      let { to, path } = item;
      if (typeOf(to) !== "object") {
        to = path;
      }
      this.$emit("on-change", to);
      this.$router.replace(to, () => {});
    }
  },
  watch: {
    $route(to) {
      //寻找所有的菜单
      const all = findAll(this.menus, to);
      this.breadMenus = this.home.path ? [this.home].concat(all) : all;
    }
  }
};
</script>
<style lang="stylus" scoped>
>>>.ivu-breadcrumb-item-separator {
  color: #a3a3a3
}
>>>.ivu-breadcrumb-item-link {
  cursor: pointer
}
.nav-bread {
  line-height: 15px
  height: 15px
  margin-left: 15px
}
.nav-bread.show { // 兄弟级别，设置class
  line-height: 35px
  height: 35px
}
</style>
